import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';

export type JwtPayload = {
  sub: number;
  username: string;
  roles: string[];
  [key: string]: any; // 允许其他属性
};

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'my_jwt_secret_key',
    });
  }

  async validate(payload: JwtPayload) {
    // 返回payload中的所有属性
    const { sub, ...rest } = payload;
    return { userId: sub, ...rest };
  }
}